#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <errno.h>

int form_get_post();

key_t key;
int msgid;

struct msgbuf
{
    long mtype;
    char mtext[1024];
};

#define MSGNAME "./msg_file"

int main()
{
    char *ret = NULL;
    // http协议
    printf("Content-Type:text/html;charset=utf-8\n\n");
    printf("\n\n");

#if 1
    key = ftok(MSGNAME, 'k');
    msgid = msgget(key, IPC_CREAT | 0655);
    if (msgid < 0)
    {
        printf("<h3>msgid_error</h3>");
        perror("msgid error!");
        exit(1);
    }
    else
    {
        printf("<h3>msgid_success:msgid = %d, %x</h3>", msgid, key);
    }

#endif

    form_get_post();
    return 0;
}

int form_get_post()
{
    char *ret = NULL;
    char *info = NULL;
    int len, i;

    // 获取请求类型 get或者post
    ret = getenv("REQUEST_METHOD");
    if (ret == NULL)
    {
        printf("获取method失败！");
        return -1;
    }
    printf("<h2>http请求形式：%s</h2>", ret);

    if (strncmp(ret, "GET", 3) == 0)
    {
        // 查看get的请求
        info = getenv("QUERY_STRING");
        if (info == NULL)
        {
            printf("获取query string失败！");
            return -1;
        }
        printf("<h3>%s的请求数据：%s</h3>", ret, info);

        struct msgbuf pmsgbuf;
        //strcpy(pmsgbuf.mtext, info);
        strcpy(pmsgbuf.mtext, "Harry");
        pmsgbuf.mtype = 3;

        if (msgsnd(msgid, (void *)&pmsgbuf, sizeof(pmsgbuf), IPC_NOWAIT) < 0) // 发送
        {
            perror("msg snd error");
        }

    }
    else if (strncmp(ret, "POST", 4) == 0)
    {
        // 查看post的请求
        // CONTENT_LENGTH 客户端向标准输入设备发送的数据长度，单位为字节
        len = atoi(getenv("CONTENT_LENGTH"));
        info = (char *)malloc(len + 1);

        for (i = 0; i < len; i++)
        {
            info[i] = (char)fgetc(stdin);
        }
        info[i] = 0;
        printf("<h3>%s的请求数据：%s</h3>", ret, info);
        free(info);
        info = NULL;
    }
    else
    {
        printf("<h3>form请求类型未知</h3>");
        return -1;
    }
    return 0;
}
